package com.social.socialservice.unit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 搜索+热搜工具类
 */
@Component
public class SearchRedisHelper {
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 热搜的key
     */
    public static final String HOT_SEARCH = "hotSearch";

    /**
     * 热搜key的过期时间
     */
    public static final Integer HOT_SEARCH_EXPIRE_TIME = 3;

    /**
     * 设置redis的过期时间
     * expire其实是懒加载，不设置key的时候是不会执行的
     */
    @PostConstruct
    public void setHotSearchExpireTime() {
        redisTemplate.expire(HOT_SEARCH, HOT_SEARCH_EXPIRE_TIME, TimeUnit.SECONDS);
    }

    /**
     * 热搜列表
     * @return
     */
    public Set<String> listHotSearch() {
        //0 5 表示0-5下标对应的元素
        return redisTemplate.opsForZSet().reverseRangeWithScores(HOT_SEARCH, 0, 10);
    }

    /**
     * redis添加热搜
     * @param query
     */
    public void addRedisHotSearch(String query) {
        //1：表示每调用一次，当前查询关键字的分数+1
        redisTemplate.opsForZSet().incrementScore(HOT_SEARCH, query, 1D);
    }
}
